<template>
  <div>
    <div style="padding: 5px 0;display: flex;justify-content: space-between;align-items: center;">
      <div style="display: flex;align-items: center;">
        <el-form inline v-model="search">
          <el-select remote filterable :remote-method="searchBrand" :loading="search.brandLoading"
            style="width: 150px;border-radius: 15px 0 0 15px" placeholder="请输入品牌关键字" v-model="search.brandName"
            size="small" clearable @change="searchSpu">
            <el-option v-for="item in search.brandOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <span style="color: #7A7A7A99;margin: 0 10px 0 10px">-</span>
          <el-select remote filterable :remote-method="searchCate" :loading="search.cateLoading"
            style="width: 150px;border-radius: 0" placeholder="请输入种类关键字" v-model="search.categoryName" size="small"
            clearable @change="searchSpu">
            <el-option v-for="item in search.cateOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <span style="color: #7A7A7A99;margin: 0 10px 0 10px">-</span>
          <el-input clearable v-model.trim="search.name" size="small" placeholder="请输入商品关键字"
            @keyup.enter.native="searchSpu" @input="searchSpu" style="width: 200px">
            <i slot="prefix" class="el-input__icon el-icon-search" style="color: #409EFF"></i>
          </el-input>
        </el-form>
      </div>
      <el-button-group>
        <el-button size="small" type="primary" @click="dialog.showAddSpu = true"
          style="transition: transform 1s ease;">新增商品</el-button>
        <transition name="el-zoom-in-top">
          <el-button v-show="showSpuBatchBtn" size="small" type="danger" @click="delBatchSpu">批量删除</el-button>
        </transition>
        <transition name="el-zoom-in-top">
          <el-button v-show="showSpuBatchBtn" size="small" type="success"
            @click="changeDiffSkuStateBatch(selection.spu, true)">批量上架</el-button>
        </transition>
        <transition name="el-zoom-in-top">
          <el-button v-show="showSpuBatchBtn" size="small" type="warning"
            @click="changeDiffSkuStateBatch(selection.spu, false)">批量下架</el-button>
        </transition>
      </el-button-group>
    </div>
    <el-table ref="spuTable" :cell-class-name="({ columnIndex }) => columnIndex === 4 ? 'shoesImage' : ''"
      :data="spuList" :expand-row-keys="expandedRowList" :header-cell-style="{ background: '#e4f1ff' }"
      @selection-change="spuSelectionChange" border highlight-current-row highlight-selection-row
      @expand-change="loadSkuList" row-key="id" stripe style="width: 100%">
      <el-table-column align="center" type="expand" width="35">
        <div slot-scope="{row}">
          <el-button-group>
            <el-button size="small" type="primary" @click="dialog.showAddSku = true">新增商品</el-button>
            <transition name="el-zoom-in-center">
              <el-button v-show="showSkuBatchBtn" size="small" type="danger" @click="delBatchSku">批量删除</el-button>
            </transition>
            <transition name="el-zoom-in-center">
              <el-button v-show="showSkuBatchBtn" size="small" type="success"
                @click="putOnShelf(selection.sku)">批量上架</el-button>
            </transition>
            <transition name="el-zoom-in-center">
              <el-button v-show="showSkuBatchBtn" size="small" type="warning"
                @click="putOffShelf(selection.sku)">批量下架</el-button>
            </transition>
            <el-button size="small" type="success" style="margin-left: auto;margin-right: 15px"
              :plain="enableSkuListHiLi" @click="enableSkuListHiLi = !enableSkuListHiLi">{{ enableSkuListHiLi ? '关闭' :
                '开启'
              }}高亮</el-button>
          </el-button-group>
          <el-table ref="skuTable" v-loading="!row.skuList"
            :cell-class-name="({ columnIndex }) => columnIndex === 3 ? 'shoesImage' : ''"
            :data="row.skuList ? row.skuList : []" :header-cell-style="{ background: 'rgba(214,236,255,0.76)' }"
            :row-style="rowHighlight" highlight-current-row highlight-selection-row max-height="600" row-key="id"
            size="mini" @selection-change="skuSelectionChange">
            <el-table-column align="center" type="index" width="30">
            </el-table-column>
            <el-table-column align="center" type="selection" width="50"></el-table-column>
            <el-table-column align="center" label="ID" prop="id" sortable width="60"></el-table-column>
            <el-table-column align="center" label="图片" width="150">
              <template slot-scope="{row:{urls}}">
                <el-image :src="urls" fit="scale-down" style="max-height: 100px"></el-image>
              </template>
            </el-table-column>
            <el-table-column align="center" label="颜色" sortable prop="attribute.color" width="180">
            </el-table-column>
            <el-table-column align="center" label="尺寸" sortable prop="attribute.size">
            </el-table-column>
            <el-table-column align="center" label="售价" sortable prop="salePrice" width="180">
            </el-table-column>
            <el-table-column align="center" label="库存" prop="stock" sortable width="180">
            </el-table-column>
            <el-table-column align="center" label="上架状态" width="80">
              <template slot-scope="{row}">
                <el-switch :value="row.state" :active-value="0" :inactive-value="1" active-color="#13ce66"
                  @change="changeSkuState(row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="100">
              <div slot-scope="{row}"
                style="height:60px;display: flex;justify-content: space-around;align-items: stretch;flex-wrap: wrap">
                <el-button plain size="mini" style="margin-bottom: 4px;width: 80px" type="primary"
                  @click="showSkuEditDialog(row)">编辑</el-button>
                <el-popconfirm title="确定删除？" @confirm="delSingleSku([row.id])">
                  <el-button slot="reference" size="mini" style="margin-left: 0;width: 80px" type="danger">删除
                  </el-button>
                </el-popconfirm>

              </div>
            </el-table-column>
          </el-table>
        </div>
      </el-table-column>
      <el-table-column align="center" type="selection" width="60"></el-table-column>
      <el-table-column align="center" label="ID" prop="id" width="60"></el-table-column>
      <el-table-column align="center" label="商品名称" show-overflow-tooltip prop="name"></el-table-column>
      <el-table-column align="center" label="图片" width="120">
        <template slot-scope="{row:{urls}}">
          <el-image :src="urls" fit="scale-down" style="max-height: 100px"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分类" prop="categoryName"></el-table-column>
      <el-table-column align="center" label="品牌" prop="brandName"></el-table-column>
      <el-table-column align="center" label="建议售价" prop="price"></el-table-column>
      <el-table-column align="center" label="商品属性" show-overflow-tooltip width="200">
        <div slot-scope="{row:{attribute}}"
          style="display: flex;flex-wrap: wrap; align-content: flex-start;width: 100%">
          <div v-for="key in Object.keys(attribute)" :key="key"
            style="display: flex;flex-wrap: wrap; align-content: flex-start;width: max-content">
            <el-tag v-for="value in attribute[key]" :key="value" size="mini">{{ value }}</el-tag>
          </div>
        </div>
      </el-table-column>
      <el-table-column align="center" label="销量" prop="sales"></el-table-column>
      <el-table-column align="center" label="创建时间" prop="createTime" width="100"></el-table-column>
      <el-table-column align="center" label="操作" width="100">
        <div slot-scope="{row}"
          style="height:60px;display: flex;justify-content: space-around;align-items: stretch;flex-wrap: wrap">
          <el-button plain size="mini" style="margin-bottom: 4px;width: 80px" type="primary"
            @click="showSpuEditDialog(row)">编辑</el-button>
          <el-popconfirm title="确定删除？" @confirm="delSingleSpu([row.id])">
            <el-button slot="reference" size="mini" style="margin-left: 0;width: 80px" type="danger">删除
            </el-button>
          </el-popconfirm>
        </div>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <el-pagination :current-page="page.pageNum" :page-size="page.pageSize" :page-sizes="[2, 5, 10]"
        :total="page.total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <!-- 新增spu弹窗   -->
    <el-dialog destroy-on-close :close-on-click-modal="false" :visible.sync="dialog.showAddSpu" title="新增商品" width="40%"
      @open="initSpuDialogData" center>
      <el-form :model="spu" :rules="rules" ref="addSpuForm">
        <el-form-item label="图片" label-width="150px">
          <el-upload ref="upload" :on-success="uploadSuccess" :action="`http://${filePath}:9999/files/upload`"
            list-type="picture" :limit="1">

            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品名称" label-width="150px" prop="name">
          <el-input v-model.trim="spu.name" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="建议售价" label-width="150px" prop="price">
          <el-input v-model.number="spu.price" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="商品品牌" label-width="150px" prop="brandName">
          <el-select v-model="spu.brandName" filterable placeholder="请选择品牌" style="width: 80%">
            <el-option v-for="item in spuData.brandList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" label-width="150px" prop="categoryName">
          <el-select v-model="spu.categoryName" filterable placeholder="请选择分类" style="width: 80%">
            <el-option v-for="item in spuData.cateList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本属性" label-width="150px" placeholder="请选择属性">
          <el-cascader :options="spuData.spuAttrOptions" :props="{ multiple: true }" collapse-tags placeholder="请选择"
            style="width: 80%" @change="changeSpuAttr">
          </el-cascader>
        </el-form-item>
        <el-form-item label="商品描述" label-width="150px">
          <el-input v-model.trim="spu.detail" autocomplete="off" style="width: 80%" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.showAddSpu = false">取 消</el-button>
        <el-button type="primary" @click="addSpu">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑spu弹窗   -->
    <el-dialog destroy-on-close :close-on-click-modal="false" :visible.sync="dialog.showEditSpu" title="编辑商品"
      width="40%" @open="initSpuDialogData" center>
      <el-form :model="editingSpu" :rules="rules" ref="editSpuForm">
        <el-form-item label="图片" label-width="150px">
          <!--          <el-upload ref="uploadEdit" :limit="1" :file-list="fileList" :on-exceed="onEditExceed" :on-success="uploadSuccessEdit"-->
          <el-upload ref="uploadEdit" :limit="1" :on-success="uploadSuccessEdit"
            :action="`http://${filePath}:9999/files/upload`" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品名称" label-width="150px" prop="name">
          <el-input v-model.trim="editingSpu.name" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="建议售价" label-width="150px" prop="price">
          <el-input v-model.number="editingSpu.price" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="商品品牌" label-width="150px" prop="brandName">
          <el-select v-model="editingSpu.brandName" filterable placeholder="请选择品牌" style="width: 80%">
            <el-option v-for="item in spuData.brandList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" label-width="150px" prop="categoryName">
          <el-select v-model="editingSpu.categoryName" filterable placeholder="请选择分类" style="width: 80%">
            <el-option v-for="item in spuData.cateList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本属性" label-width="150px" placeholder="请选择属性">
          <el-cascader v-model="selectedAttr" :options="spuData.spuAttrOptions" :props="{ multiple: true }"
            collapse-tags placeholder="请选择" style="width: 80%" @change="changeSpuAttrEdit">
          </el-cascader>
        </el-form-item>
        <el-form-item label="商品描述" label-width="150px">
          <el-input v-model.trim="editingSpu.detail" autocomplete="off" style="width: 80%" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.showEditSpu = false">取 消</el-button>
        <el-button type="primary" @click="editSpu">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增sku弹窗   -->
    <el-dialog destroy-on-close :close-on-click-modal="false" :visible.sync="dialog.showAddSku" title="新增商品" width="35%"
      @open="initSkuDialogData" center>
      <el-form :model="sku" :rules="rules" ref="addSkuForm" label-width="100px" style="margin: 0 auto">
        <el-form-item label="图片">
          <el-upload ref="upload" :on-success="uploadSuccessSku" :action="`http://${filePath}:9999/files/upload`"
            list-type="picture" :limit="1">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="定价" prop="salePrice">
          <el-input-number v-model.number="sku.salePrice" autocomplete="off" style="width: 70%"></el-input-number>
        </el-form-item>
        <el-form-item label="尺码" prop="attribute.size">
          <el-select v-model="sku.attribute.size" filterable placeholder="请选择尺码" style="width: 70%">
            <el-option v-for="item in skuData.sizeList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="attribute.color">
          <el-select v-model="sku.attribute.color" filterable placeholder="请选择颜色" style="width: 70%">
            <el-option v-for="item in skuData.colorList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model.number="sku.stock" :min="1" autocomplete="off" style="width: 70%"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.showAddSku = false">取 消</el-button>
        <el-button type="primary" @click="addSku">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑sku弹窗   -->
    <el-dialog destroy-on-close :close-on-click-modal="false" :visible.sync="dialog.showEditSku" title="编辑商品"
      width="40%" @open="initSkuDialogData" center>
      <el-form :model="editingSku" :rules="rules" ref="editSkuForm" label-width="100px" style="margin: 0 auto">
        <el-form-item label="图片">
          <el-upload ref="upload" :on-success="uploadSuccessSkuEdit" :action="`http://${filePath}:9999/files/upload`"
            list-type="picture" :limit="1">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="定价" prop="salePrice">
          <el-input-number v-model.number="editingSku.salePrice" autocomplete="off"
            style="width: 70%"></el-input-number>
        </el-form-item>
        <el-form-item label="尺码" prop="size">
          <el-select v-model="editingSku.attribute.size" filterable placeholder="请选择尺码" style="width: 70%">
            <el-option v-for="item in skuData.sizeList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-select v-model="editingSku.attribute.color" filterable placeholder="请选择颜色" style="width: 70%">
            <el-option v-for="item in skuData.colorList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model.number="editingSku.stock" autocomplete="off" style="width: 70%"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.showEditSku = false">取 消</el-button>
        <el-button type="primary" @click="editSku">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addSku,
  addSpu,
  deleteSku,
  deleteSpu,
  getBasicSpuAttr,
  getBrandList,
  getCateList,
  getSizeAndColorList,
  getSkuList,
  getSpuListBack,
  putAllSkuOffBatch,
  putAllSkuOnBatch,
  putSkuOff,
  putSkuOn,
  searchBrandName,
  searchCateName,
  updateSku,
  updateSpu
} from "@/api/goods";
import { getUser } from "@/utils/storage";
import { validateGoodsName, validatePrice, validateStock } from "@/utils/validator";
import { proFilePath, devFilePath } from "../../utils/filePath";
export default {
  name: "Goods",
  data() {
    return {
      search: {
        //商品名
        name: '',
        brandName: '',
        categoryName: '',
        //品牌搜索下拉框
        brandOptions: [],
        //种类搜索下拉框
        cateOptions: [],
        brandLoading: false,
        cateLoading: false
      },
      // fileList: [],
      user: {},
      // 当前展开行Id数组
      expandedRowList: [],
      spuList: [],
      showSkuBatchBtn: false,
      showSpuBatchBtn: false,
      page: {
        pageNum: 1,
        pageSize: 5,
        total: 0
      },
      spu: {},
      sku: { attribute: { color: null, size: null } },
      editingSpu: {},
      editingSku: { attribute: { color: null, size: null } },
      //spu新增、修改对话框时要加载的数据
      spuData: {
        spuAttrOptions: [],
        brandList: [],
        cateList: [],
      },
      //sku新增、修改对话框时要加载的数据
      skuData: {
        sizeList: [],
        colorList: []
      },
      //保存spu和sku被选择的行的id
      selection: {
        spu: [],
        sku: []
      },
      attrMap: { material: '材料', function: '功能', assurance: '保障', people: '适用人群' },
      selectedAttr: [],
      dialog: {
        //新增spu
        showAddSpu: false,
        //修改spu
        showEditSpu: false,
        //新增sku
        showAddSku: false,
        //修改sku
        showEditSku: false
      },
      enableSkuListHiLi: false,
      filePath: proFilePath
    }
  },
  computed: {
    rules() {
      return {
        name: { required: true, trigger: 'blur', validator: validateGoodsName },
        price: { required: true, trigger: 'blur', validator: validatePrice },
        brandName: { required: true, trigger: 'blur', message: '请选择品牌' },
        categoryName: { required: true, trigger: 'blur', message: '请选择种类' },
        'attribute.size': { required: true, trigger: 'blur', message: '请选择尺码' },
        'attribute.color': { required: true, trigger: 'blur', message: '请选择颜色' },
        salePrice: { required: true, trigger: 'blur', validator: validatePrice },
        stock: { required: true, trigger: 'blur', validator: validateStock },
      }
    }
  },
  created() {
    this.user = getUser()
    this.loadSpuList()
  },
  methods: {
    //初始化spu属性
    initSpuAttrOptions() {
      getBasicSpuAttr().then(res => {
        //[{label:"材料",value:"material",children:[{label:"帆布"，value:"帆布"},{label:"塑料"，value:"塑料"}]},{}]
        if (res.code === '0') {
          let labelList = Object.keys(res.data)
          this.spuData.spuAttrOptions = labelList.filter(label => label !== "size" && label !== "color").map(label => {
            let obj = {}
            //由于基本属性是级联下拉列表，所以要将第一级的material等英文映射为中文
            obj.label = this.attrMap[label]
            obj.value = label
            let childrenArray = res.data[label] //childrenArray ===> ["帆布"，"塑料"]
            if (childrenArray) {
              console.log(childrenArray)
              obj.children = childrenArray.map(child => {
                let obj = {}
                obj.label = child
                obj.value = child
                return obj
              })
            }
            return obj
          })
        }
      })
    },
    //初始化新增或修改spu的对话框的数据
    initSpuDialogData() {
      this.spu = {}
      //由于spu的属性需要二次封装为vo且比较繁琐，所以单独写一个函数
      getBrandList().then(res => {
        if (res.code === '0') {
          this.spuData.brandList = res.data.map(brand => brand.name)
        }
      })
      getCateList().then(res => {
        if (res.code === '0') {
          this.spuData.cateList = res.data.map(category => category.name)
        }
      })
      this.initSpuAttrOptions()
    },
    //初始化新增或修改sku的对话框的数据
    initSkuDialogData() {
      this.sku = { attribute: { color: null, size: null } }
      //设置sku的spuId
      this.sku.spuId = this.expandedRowList[0]
      //设置sku的参考价格
      this.sku.price = this.spuList.find(spu => spu.id === this.expandedRowList[0]).price
      //获取颜色和尺码下拉列表的值
      getSizeAndColorList().then(res => {
        if (res.code === '0') {
          this.skuData.colorList = res.data.color
          this.skuData.sizeList = res.data.size
        }
      })
    },
    changeSpuAttr(selectedAttrList) {
      this.spu.attribute = JSON.stringify(this.convertArrayToObject(selectedAttrList))
    },
    changeSpuAttrEdit(selectedAttrList) {
      this.editingSpu.attribute = JSON.stringify(this.convertArrayToObject(selectedAttrList))
    },
    convertArrayToObject(arr) {
      const result = {};
      for (const [key, value] of arr) {
        if (!result[key]) {
          result[key] = [];
        }
        result[key].push(value);
      }
      return result;
    },
    convertObjectToArray(obj) {
      let resultArray = []
      for (const key in obj) {
        obj[key].forEach(value => {
          resultArray.push([key, value]);
        });
      }
      return resultArray;
    },
    //在搜索spu时，用户可以键入品牌关键字搜索品牌以填充品牌搜索框
    searchBrand(keyword) {
      this.search.brandLoading = true
      searchBrandName(keyword).then(res => {
        if (res.code === '0') {
          this.search.brandOptions = res.data.map(brand => {
            let obj = {}
            obj.label = brand.name
            obj.value = brand.name
            return obj
          })
        }
        this.search.brandLoading = false
      })
    },
    //在搜索spu时，用户可以键入种类关键字搜索种类以填充种类搜索框
    searchCate(keyword) {
      this.search.cateLoading = true
      searchCateName(keyword).then(res => {
        if (res.code === '0') {
          this.search.cateOptions = res.data.map(category => {
            let obj = {}
            obj.label = category.name
            obj.value = category.name
            return obj
          })
        }
        this.search.cateLoading = false
      })
    },
    uploadSuccessSku(res) {
      this.sku.urls = `http://${this.filePath}:9999/files/` + res.data
    },
    uploadSuccessSkuEdit(res) {
      this.editingSku.urls = `http://${this.filePath}:9999/files/` + res.data
    },
    uploadSuccess(res) {
      this.spu.urls = `http://${this.filePath}:9999/files/` + res.data
    },

    uploadSuccessEdit(res, file) {
      this.editingSpu.urls = `http://${this.filePath}:9999/files/` + res.data
      // this.fileList.pop()
      // this.fileList.push(file)
      // console.log(this.fileList)
    },
    // onEditExceed(files,fileList){
    //   this.$set(fileList[0], 'raw', files[0]);//raw就是指文件
    //   this.$set(fileList[0], 'name', files[0].name);//name就是指文件名
    //   this.$refs.uploadEdit.clearFiles();//删除所有上传的文件
    //   this.$refs.uploadEdit.handleStart(files[0]);//handleStart()指的是手动选择文件，Element Plus 的el-upload有说明
    //   this.$refs.uploadEdit.submit();//手动上传
    // },
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize
      this.loadSpuList()
    },
    handleCurrentChange(pageNum) {
      this.page.pageNum = pageNum
      this.loadSpuList()
    },
    spuSelectionChange(selectedRows) {
      this.showSpuBatchBtn = selectedRows.length
      this.selection.userspu = selectedRows.map(spu => spu.id)
    },
    skuSelectionChange(selectedRows) {
      this.showSkuBatchBtn = selectedRows.length;
      this.selection.sku = selectedRows.map(sku => sku.id)
    },
    changeSkuState(row) {
      if (!row.state) {
        // sku当前为上架状态
        this.putOffShelf([row.id])
      } else {
        // sku当前为下架状态
        this.putOnShelf([row.id])
      }
    },
    //spu批量上架、下架,即上/下架多个spu下的所有sku
    changeDiffSkuStateBatch(spuIdList, isPutOn) {
      if (isPutOn) {
        //批量上架
        putAllSkuOnBatch(spuIdList).then(res => {
          if (res.code === '0') {
            //如果批量上下架的spu中有当前展开
            this.$message.success('上架成功')
            this.loadSpuList()
            if (this.expandedRowList[0]) {
              this.loadSkuListForce(this.expandedRowList[0])
            }
          }
        })
      } else {
        //批量下架
        putAllSkuOffBatch(spuIdList).then(res => {
          if (res.code === '0') {
            this.$message.success('下架成功')
            this.loadSpuList()
            if (this.expandedRowList[0]) {
              this.loadSkuListForce(this.expandedRowList[0])
            }
          }
        })
      }
    },
    //上架商品，只能上架同一spu下的sku
    putOnShelf(arr) {
      putSkuOn(arr).then(res => {
        if (res.code === '0') {
          this.$message.success('上架成功')
          if (this.expandedRowList[0]) {
            this.loadSkuListForce(this.expandedRowList[0])
          }
        }
      })
    },
    //下架商品，只能下架同一spu下的sku
    putOffShelf(var1) {
      putSkuOff(var1).then(res => {
        if (res.code === '0') {
          this.$message.success('下架成功')
          if (this.expandedRowList[0]) {
            this.loadSkuListForce(this.expandedRowList[0])
          }
        }
      })
    },
    addSpu() {
      this.$refs.addSpuForm.validate(valid => {
        if (valid) {
          addSpu(this.spu).then((res) => {
            if (res.code === '0') {
              this.$message.success('新增成功')
              this.loadSpuList()
            }
            //关闭对话框
            this.dialog.showAddSpu = false
          })
        }
      })
    },
    delSingleSpu(arr) {
      deleteSpu(arr).then(res => {
        if (res.code === '0') {
          this.$message.success('删除成功')
          //如果当前删除的spu是本页的唯一一个,则将当前页-1从而获取前面一页的spu
          if (this.spuList.length === 1) {
            this.page.pageNum--
          }
          this.loadSpuList()
        }
      })
    },
    delBatchSpu() {
      deleteSpu(this.selection.spu).then(res => {
        if (res.code === '0') {
          this.$message.success('删除成功')
          //如果当前删除的spu是本页的唯一一个,则将当前页-1从而获取前面一页的spu
          if (this.spuList.length === 1) {
            this.page.pageNum--
          }
          this.loadSpuList()
        }
      })
    },
    editSpu() {
      this.$refs.editSpuForm.validate(valid => {
        if (valid) {
          if (this.editingSpu.attribute instanceof Object)
            this.editingSpu.attribute = JSON.stringify(this.editingSpu.attribute)
          updateSpu(this.editingSpu).then((res) => {
            if (res.code === '0') {
              this.$message.success('修改成功')
              this.editingSpu = {}
              this.loadSpuList()
            }
            //关闭对话框
            this.dialog.showEditSpu = false
          })
        }
      })
    },
    searchSpu() {
      //输入关键字后重置pageNum
      this.page.pageNum = 1
      this.loadSpuList()
    },
    loadSpuList() {
      getSpuListBack(this.search, this.page).then(res => {
        if (res.code === '0') {
          //当展开了skuList后新增或编辑spu后会刷新spuList,从而导致skuList消失，使得页面一直加载
          //更新spu之前把当前展开行的skuList设置进去cd
          let expandedSpu = this.spuList.find(spu => spu.id === this.expandedRowList[0])
          if (expandedSpu) {
            let resSpu = res.data.records.find(spu => spu.id === expandedSpu.id)
            if (resSpu)
              resSpu.skuList = expandedSpu.skuList
          }
          this.spuList = res.data.records
          //更新总数据条数
          this.page.total = res.data.total
        }
      })
    },
    showSpuEditDialog(row) {
      //初始化editingSpu旧的值,深度拷贝避免修改原spu的值
      this.editingSpu = JSON.parse(JSON.stringify(row))
      // this.fileList.push({name: '旧的', url: row.urls})
      this.selectedAttr = this.convertObjectToArray(row.attribute)
      this.dialog.showEditSpu = true
    },
    showSkuEditDialog(row) {
      //初始化editingSku旧的值,深度拷贝避免修改原sku的值
      this.editingSku = JSON.parse(JSON.stringify(row))
      this.dialog.showEditSku = true
    },
    addSku() {
      this.$refs.addSkuForm.validate(valid => {
        if (valid) {
          this.sku.attribute = JSON.stringify(this.sku.attribute)
          addSku(this.sku).then(res => {
            if (res.code === '0') {
              this.$message.success('新增成功')
              if (this.expandedRowList[0]) {
                this.loadSkuListForce(this.expandedRowList[0])
              }
            }
            this.dialog.showAddSku = false
          })
        }
      })
    },
    delSingleSku(arr) {
      deleteSku(arr).then(res => {
        if (res.code === '0') {
          this.$message.success('删除成功')
          if (this.expandedRowList[0]) {
            this.loadSkuListForce(this.expandedRowList[0])
          }
        }
      })
    },
    delBatchSku() {
      deleteSku(this.selection.sku).then(res => {
        if (res.code === '0') {
          this.$message.success('删除成功')
          if (this.expandedRowList[0]) {
            this.loadSkuListForce(this.expandedRowList[0])
          }
        }
      })
    },
    editSku() {
      this.$refs.editSkuForm.validate(valid => {
        if (valid) {
          this.editingSku.attribute = JSON.stringify(this.editingSku.attribute)
          updateSku(this.editingSku).then(res => {
            if (res.code === '0') {
              this.$message.success('修改成功')
              this.editingSku = { attribute: { color: null, size: null } }
              if (this.expandedRowList[0]) {
                this.loadSkuListForce(this.expandedRowList[0])
              }
            }
            this.dialog.showEditSku = false
          })
        }
      })
    },
    loadSkuList(row) {
      let spuId = row.id
      let expandedId = this.expandedRowList.length ? this.expandedRowList[0] : 0
      //展开和收起都会调用该方法
      //如果点击行和当前展开行一样代表收起操作，直接return
      if (spuId === expandedId)
        return
      //将当前行设置为高亮
      this.$refs.spuTable.setCurrentRow(row)
      // console.log('要展开的行',spuId,'当前展开行',expandedId)
      //如果点击了其他行(row为点击的行,expandedId的spu是当前展开的行)且点击的行没有加载过skuList
      if (expandedId != spuId && !row.skuList) {
        this.loadSkuListForce(spuId)
      }
      //如果点击了其他行，但是那一行已经加载过了skuList
      else if (expandedId != spuId) {
        //手动收起当前行
        this.$refs.spuTable.toggleRowExpansion(this.spuList.find(spu => spu.id == expandedId), false)
      }
      //删除当前展开的行
      this.expandedRowList.pop()
      //将点击行设置为展开行
      this.expandedRowList.push(spuId)
    },
    //不管点击的行是不是当前展开行都刷新skuList
    loadSkuListForce(spuId) {
      getSkuList(spuId).then(res => {
        if (res.code === '0') {
          //找到要刷新的spu
          let spu = this.spuList.find(item => item.id === spuId)
          //spu为this.spuList的某个元素即某个spu
          this.$set(spu, 'skuList', res.data.map(sku => { return { ...sku, attribute: JSON.parse(sku.attribute) } }))
          console.log('强制刷新', spu.id, '的skuList')
        }
      })
    },
    rowHighlight({ row }) {
      if (!this.enableSkuListHiLi)
        return { background: 'rgb(236,245,255)' }
      else if (row.state === 0)
        return { 'background': 'rgba(222,255,204,0.65)' }
      else
        return { 'background': 'rgba(222,222,222,0.27)' }
    }
  }
};
</script>

<style>
/* 不能写scoped,否侧会不生效 */
/* 这个样式是去掉第二列的padding */

.shoesImage {
  padding: 1px !important;
}

.shoesImage .cell {
  padding: 1px;
  overflow: unset;
  display: flex;
  align-items: center;
}

.el-cascader-menu:first-of-type {
  .el-cascader-node {
    .el-checkbox {
      display: none;
    }
  }
}

/* 设置默认的背景色（如果需要的话） */
.el-table tbody tr>td {
  background-color: unset;
}

/* 设置所有行悬停时的背景色 */
.el-table tbody tr:hover>td {
  background-color: unset !important;
}

/* 排除带有 .expanded 类的行和紧接着它的下一行在悬停时的背景色改变 */
.expanded+tr,
.expanded+tr:hover {
  background: rgb(236, 245, 255);
  border: 2px solid red;
}
</style>
